package com.atguigu.mybatis.test;

import javax.sql.DataSource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.jndi.JndiObjectFactoryBean;

import com.alibaba.druid.pool.DruidDataSource;

public class GetDatasource {
	private Logger logger = LogManager.getLogger(getClass());

	public static DataSource getInstance(String driver, String url, String user, String password, String validTable) {
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setDriverClassName(driver);
		dataSource.setUrl(url);
		dataSource.setUsername(user);
		dataSource.setPassword(password);
		dataSource.setInitialSize(1);
		dataSource.setMaxActive(20);
		dataSource.setMaxWait(60000);
		dataSource.setTimeBetweenEvictionRunsMillis(30000);
		dataSource.setMinEvictableIdleTimeMillis(180000);
		dataSource.setTestWhileIdle(true);
		dataSource.setValidationQuery("select * from " + validTable);
		dataSource.setTestOnBorrow(false);
		dataSource.setTestOnReturn(false);
		dataSource.setPoolPreparedStatements(false);
		dataSource.setMaxOpenPreparedStatements(-1);
		dataSource.setMaxPoolPreparedStatementPerConnectionSize(-1);
		dataSource.setRemoveAbandoned(false);
		return dataSource;
	}

	public DataSource getInstance(String jndi) {

		try {
			JndiObjectFactoryBean jndiObjectFactoryBean = new JndiObjectFactoryBean();
			jndiObjectFactoryBean.setJndiName(jndi);
			jndiObjectFactoryBean.afterPropertiesSet();
			DataSource ds = (DataSource) jndiObjectFactoryBean.getObject();
			if (ds != null) {
				return ds;
			}
		} catch (Exception e) {
			logger.error("getDataSource(String) - jndi=" + jndi, e); //$NON-NLS-1$
		}

		try {
			JndiObjectFactoryBean jndiObjectFactoryBean = new JndiObjectFactoryBean();
			jndiObjectFactoryBean.setJndiName(jndi);
			jndiObjectFactoryBean.setResourceRef(true);
			jndiObjectFactoryBean.afterPropertiesSet();
			DataSource ds = (DataSource) jndiObjectFactoryBean.getObject();
			if (ds != null) {
				return ds;
			}
		} catch (Exception e) {
			logger.error("getDataSource(String)  setResourceRef(true)- jndi=" + jndi, e); //$NON-NLS-1$
		}

		logger.error("不能获取JNDI连接  getDataSource(String) - jndi=" + jndi);
		return null;

	}
}
